<template>
<div class="all-page-heiht">
   <el-row class="goods-list-title"><h1>活动列表</h1> </el-row>
  <el-card class="el-card-allheight">
    <el-table
     v-loading="loading"
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
    >
    <!-- t推送栏 -->
    <el-table-column label="推送">
        <template #default="props">
          <!-- 未结束 -->
          <div v-if="props.row.status!==1">
             <el-button
              type="info"
              round
              size="small"
              v-if="props.row.isShow == 0"
              @click="putOutBtn(props.row)"
              ><el-icon><video-play /></el-icon> 开始推送</el-button>
            <el-button
              type="warning"
              round
              size="small"
              v-else
              @click="putStopOutBtn(props.row)"
              ><el-icon><video-play /></el-icon> 取消推送</el-button>
          </div>
          <div v-else>
              <el-button  size="small" type="danger" round :disabled="true" ><el-icon><video-play /></el-icon> 活动结束</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="activityName" label="活动名称" />
      <el-table-column
        prop="activityStartTime"
        label="活动开始时间"
        width="186"
      />
      <!-- 活动内容 -->
      <el-table-column label="活动内部">
        <template #default="props">
                <el-button size="small" round type="primary" @click="ActivityDetailBtn(props.row)">
              <el-icon><goods /></el-icon>活动详情</el-button
            >
        </template>
      </el-table-column>
      <el-table-column prop="activityLastTime" label="活动持续时间" />
      <!-- 规则栏 -->
      <el-table-column label="准入规则配置">
            <template #default="prop">
               <el-button v-if="prop.row.ruleId==null" type="info" size="small" effect="dark" @click="ruleConfigBtn(prop.row.id)">点击配置</el-button>
               <el-button v-else type="success" size="small" @click="ruleCheckBtn(prop.row.ruleId)">点击查看</el-button>
            </template>
      </el-table-column>
      <!-- 状态栏 -->
      <el-table-column label="活动状态">
        <template #default="props">

          <el-tag effect="dark" type="success" v-if="props.row.isShow ==1"
            ><el-icon><clock/></el-icon>申请状态</el-tag
          >
          <el-tag type="info" effect="dark" v-else> <el-icon><clock/></el-icon>没有推送</el-tag>
        
        </template>
      </el-table-column>
      <!-- 操作栏 -->
      <el-table-column label="操作" width="300">
        <template #default="props">
          <!-- 结束的 -->
         <div v-if="props.row.status==1">
            <el-button
              type="warning"
              size="small"
              round
              @click="bookRecordBtn(props.row.id)"
            >
              <el-icon><document /></el-icon>活动记录</el-button
            >
          
         </div>

         <!-- 未结束的 -->
          <div v-else>
          <!-- 未发布的 -->
          <div v-if="props.row.isShow == 0">
         
            <el-button
             v-if="props.row.status==0&&props.row.isShow==0"
              type="danger"
              @click="activityDeleteBtn(props.row)"
              round
              size="small"
            >
              <el-icon><delete /></el-icon> 删除活动</el-button
            >
          </div>
          <div v-else>
            <el-button
              type="warning"
              size="small"
              round
              @click="bookRecordBtn(props.row.id)"
            >
              <el-icon><document /></el-icon>活动记录</el-button
            >
            <el-button
            v-if="props.row.status==0&&props.row.isShow==0"
               type="danger"
              @click="activityDeleteBtn(props.row)"
              round
              size="small"
               
            >
              <el-icon><delete /></el-icon> 删除活动</el-button
            >
          </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row class="el-row-center">
    <el-pagination
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    </el-row>
    <!-- 预约详情弹出框 -->
    <el-dialog v-model="activityBookDialogVisible"  title="申请记录" >
       <template #default>
      <el-row><span>目前预约人数:</span><span>{{bookRecord_total}}</span></el-row>
      <el-table :data="bookRecordsData">
        <el-table-column
          property="createTime"
          label="申请时间"
         
        ></el-table-column>
         <el-table-column
          property="userName"
          label="申请用户"
         
        ></el-table-column>
        <el-table-column
          property="status"
          label="当前活动状态"
         
        ></el-table-column>
        <el-table-column label="秒杀详情">
            <template #default="props">
                <el-button size="small" type="primary" v-loading="Btnloading" @click="OrderDetailBtn(props.row)">详情</el-button>
            </template>
        </el-table-column>
      </el-table>
        <el-row class="el-row-center"> <el-pagination
              :page-size="bookRecord_pageSize"
              layout="total, prev, pager, next"
              :total="bookRecord_total"
              @current-change="book_handleCurrentChange"
          >
      </el-pagination></el-row> 
       <template>
          <el-dialog  v-model="OrderDialogVisible" :append-to-body="true">
          <el-row> 当前订单号：{{orderId}} </el-row>
           <el-row> 订单产生时间：{{orderCreateTime}} </el-row>
            <el-row> 当前订单产品价格：{{price}} </el-row>
             <el-row> 当前订单修改时间：{{orderEditTime}} </el-row>
          </el-dialog>
       </template>
  
      </template>
    </el-dialog>

  
    <!-- 活动内容弹出框 -->
    <el-dialog v-model="activityContentDialogVisible" title="活动内容">
      <el-table :data="Activitycontent" :show-header="false"  style="width: 100%" >
        <el-table-column  prop="label"></el-table-column>
        <el-table-column >
           <template #default="prop">
             <span> {{detailContentData[prop.row.value]}} </span>
           </template>
        </el-table-column>
      </el-table>
    </el-dialog>

   <!-- 规则配置 -->
     <el-dialog v-model="ruleConfigDialogVisible" width="30%" title="准入规则配置">
        <el-checkbox
      v-model="checkAllRules"
    :indeterminate="isIndeterminate"
    @change="handleCheckAllChange"
    >全选</el-checkbox
  >
  <el-checkbox-group
    v-model="checkedRulesArray"
    @change="handleCheckedRulesChange"
  >
     <el-row v-for="item in accessbleRulelist" :key="item.id" >
      <el-checkbox size="large" :label="item">{{
      item.ruleName
    }}</el-checkbox>
     </el-row>
  </el-checkbox-group> 
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="ruleConfigDialogVisible=false">取消</el-button>
            <el-button type="primary" @click="confirmAddRulesBtn">确定添加</el-button>
          </span>
        </template>
    </el-dialog>
   <!-- 规则查看 -->
    <el-dialog v-model="ruleCheckDialogVisible" width="30%" title="已配置准入规则查看">
        <el-row v-for="item in activityRules"  :key="item">
                <span class="rules-font-style"> {{item}} </span>
        </el-row>
    </el-dialog>
  </el-card>
</div>
</template>
<script lang="ts">
import {analysRules }  from '@/utils/algorithm/index'
import { defineComponent, ref, reactive, onMounted, toRefs } from "vue";
import {
  ApiEditActivity,
  ApiDeleteActivity,
  ApiGetActivityList,
  ApiGetRulesList,
  ApiPutActivityRule,
  ApiPushActivity,
  ApiGetActivityDetail,
  ApiGoodsDetail,
  ApiBookRecords,
  ApiCancelActivity,
  ApiGetOrderUserandAcvityApply
} from "@/api/index";
import { ElMessageBox } from "element-plus";
import { errorMessage, infoMessage, successMessage } from "@/utils/messageTips";
import { useStore } from "vuex"
export default defineComponent({
  name: "ActivityInit",
  setup() {
    const storeArray = useStore().getters.allrules
    let tableData = ref();
    interface IGActivityRulePut{
      ruleIds:string|null,
      activityId:number|null,
      value:number|null
    }
    let activityRulesFormPut:IGActivityRulePut = {
      ruleIds:"",
      activityId:0,
      value:0
    }
    // 页面配置参数

    let usedInfo = reactive<IGPageInfo>({
      pageNum: 1,
      total: 2,
      pages: 2,
      pageSize: 15,
    });
    let BookRecord_pageInfo = reactive({
      bookRecord_id:1,
      bookRecord_pageNum: 1,
      bookRecord_total: 2,
      bookRecord_pages: 2,
      bookRecord_pageSize: 15,
    })
   // 所有对话视窗
    const AllDialogVisible= reactive<Record<string,boolean>>({

          activityContentDialogVisible:false,
          activityBookDialogVisible:false,
          // 规则查看窗口
          ruleCheckDialogVisible:false,
          // 规则配置窗口
          ruleConfigDialogVisible:false,
          // 订单弹框
          OrderDialogVisible:false
    })
   //规则获取
   const AllcheckBoxData = reactive({
       checkAllRules:false,
       checkedRules:false,
       isIndeterminate:false,
      
   })
  //  可选规则数组
   let accessbleRulelist = ref<Array<any>>([])
   let checkedRulesArray = ref<Array<any>>([])
  //  全选处理函数
   const handleCheckAllChange = (val:boolean)=>{
      checkedRulesArray.value = val ? accessbleRulelist.value : []
     AllcheckBoxData.isIndeterminate = false
   }
  //  单选处理函数
  const  handleCheckedRulesChange = (valCheckedArray:Array<any>)=>{
      const checkedLen = valCheckedArray.length
      AllcheckBoxData.checkAllRules = checkedLen === accessbleRulelist.value.length
      AllcheckBoxData.isIndeterminate = checkedLen > 0 && checkedLen < accessbleRulelist.value.length
  }
 let   Btnloading = ref<boolean>(false)
  // 根据id匹配处理后的规则
  
   const getRulesList = async ()=>{
     const {data:res} = await ApiGetRulesList() as Record<string,any>
     accessbleRulelist.value = res.filter(
       (item:any)=>item.status==1
     )
   } 
  //  规则查看
  let activityRules = ref<Array<string>>()
  const ruleCheckBtn = (val:any)=>{
       let tempArray = val.split(',')
   activityRules.value = analysRules(storeArray,tempArray) 
    
     AllDialogVisible.ruleCheckDialogVisible =true
  }
  //  规则配置
  const ruleConfigBtn = (id:number)=>{
    activityRulesFormPut.activityId = id
     AllDialogVisible.ruleConfigDialogVisible =true
  }
  // 确定添加按钮
  const confirmAddRulesBtn = async ()=>{
    // 流程数据处理
    let tempvalue = 0
    let tempArray = Array<any>()
    
    checkedRulesArray.value.forEach((item)=>{
            tempvalue += item.value
            tempArray.push(item.id)
    })
    activityRulesFormPut.ruleIds = tempArray.toString()
    activityRulesFormPut.value = tempvalue
    try{
    const res = await ApiPutActivityRule(activityRulesFormPut) as Record<string,any>
    successMessage(res.message)
    getTableData()
    checkedRulesArray.value = []
    AllDialogVisible.ruleConfigDialogVisible =false

    }catch(err){
      
      errorMessage("网络发生错误！！！")
    }
  }

   // 加载函数
    let loading = ref<boolean>(true)
    // 获取表格数据
    const getTableData = async () => {
      loading.value=true
      const { data: res } = (await ApiGetActivityList(
        usedInfo.pageNum
      )) as Record<string, any>;
      tableData.value = res.list;
      usedInfo.total = res.total;
      usedInfo.pages = res.pages;
      usedInfo.pageSize = res.pageSize
      loading.value = false
      
    };
    // 改变页码
    const handleCurrentChange = (val: number) => {
      
      usedInfo.pageNum = val;
      getTableData();
    };
    // 删除单条活动信息按钮
    const activityDeleteBtn = async (activityInfo: any) => {
      let name = activityInfo.activityName;
      let id = activityInfo.id;
      ElMessageBox.confirm(`你确定将删除活动${name}吗？`, "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消删除",
        type: "warning",
      })
        .then(async () => {
          const res = (await ApiDeleteActivity(id)) as Record<string, any>;

          successMessage("删除" + res.message);
          getTableData();
        })
        .catch(() => {
          infoMessage("您取消了删除");
        });
    };

    // 发布
    const putOutBtn = (info: any) => {
      loading.value =true
      const name = info.activityName;
      let id  = info.id
      ElMessageBox.confirm(`你确定将活动${name}推送了吗？`, "提示", {
        confirmButtonText: "推送",
        cancelButtonText: "再想想",
        type: "warning",
      })
        .then(async () => {
         const res = await ApiPushActivity(id)
          getTableData();
          
          successMessage("已经成功发放至客户端！");
        })
        .catch(() => {
          infoMessage("你取消了发布!");
        });
        loading.value =false
    };
  //  取消推送
  const putStopOutBtn = (info:any)=>{
    loading.value =true
    const name = info.activityName;
      let id  = info.id
      ElMessageBox.confirm(`你确定将活动${name}停止发布吗？`, "提示", {
        confirmButtonText: "停止推送",
        cancelButtonText: "再想想",
        type: "error",
      })
        .then(async () => {
         const res = await ApiCancelActivity(id)
          getTableData();
          
          errorMessage("已经成功停止了推送！");
        })
        .catch(() => {
          infoMessage("你取消了操作!");
        });
        loading.value =false
  } 

    // 预约详情操作区
    let bookRecordsData = ref([])
    let orderContent = reactive<{
      orderCreateTime:string,
      orderId:string,
      price:number,
      orderEditTime:string

    }>({
      orderCreateTime:"",
      orderId:"",
      price:0,
      orderEditTime:""
    })
    const getBookRecords = async (id:number)=>{
        const {data:res} = await ApiBookRecords(BookRecord_pageInfo.bookRecord_pageNum,id) as Record<string,any>
        bookRecordsData.value = res.list
        BookRecord_pageInfo.bookRecord_pageSize = res.pageSize
        BookRecord_pageInfo.bookRecord_pages = res.pages
        BookRecord_pageInfo.bookRecord_total = res.total
      
    }
    //  预约订单
    const OrderDetailBtn = async (info)=>{
      Btnloading.value = true
      try{
     const res = await ApiGetOrderUserandAcvityApply(info.userId,info.activityId)  as Record<string,any>
       
        
        Object.keys(orderContent).forEach((key)=>{
          orderContent[key]= res.data[key]
           
        })
        AllDialogVisible.OrderDialogVisible =true
        
          
        }catch(err){
          
          errorMessage("后台没这信息,看下数据库")
        }
        Btnloading.value= false
        
    }


       // 预约对话框改变页码
    const book_handleCurrentChange = (val: number) => {
      
      BookRecord_pageInfo.bookRecord_pageNum = val;
      getBookRecords(BookRecord_pageInfo.bookRecord_id);
    };
    const bookRecordBtn = async (activityid:number)=>{
        BookRecord_pageInfo.bookRecord_pageNum = 1
        BookRecord_pageInfo.bookRecord_id = activityid
        await getBookRecords(activityid)
        AllDialogVisible.activityBookDialogVisible = true
    }
    
    // 活动内容操作区
    let detailContentData = ref({})
    const ActivityDetailBtn = async (info:any)=>{
       let goodId = info.goodId
       let activityId = info.id
       loading.value = true
      const {data:activityRes} = await ApiGetActivityDetail(activityId) as Record<string,any>
      const {data:goodres} = await ApiGoodsDetail(goodId) as Record<string,any>
     detailContentData.value = {...activityRes,...goodres}
     loading.value = false
     AllDialogVisible.activityContentDialogVisible = true
    }
    const Activitycontent = [
       { label: "活动名称", value: "activityName" },
       { label: "活动规则", value: "activityRule" },
        { label: "活动详情", value: "activityDetail" },
      { label: "活动结束时间", value: "activityEndTime" },
      { label: "挂载产品", value: "goodName" },
      { label: "产品详情", value: "goodDetail" },
      { label: "产品价格", value: "goodPrice" },
      { label: "产品现有量", value: "goodStock" },
      { label: "产品使用手册介绍", value: "manual" },
      { label: "客户须知", value: "notice" },
      { label: "产品限购量", value: "limitNum" },
    ];

    // 钩子函数
    onMounted(() => {
      getTableData();
      getRulesList()
    });

    return {
      tableData,
      ...toRefs(usedInfo),
      ...toRefs(AllDialogVisible),
      ...toRefs(AllcheckBoxData),
      ...toRefs(BookRecord_pageInfo),
      handleCurrentChange,
      activityDeleteBtn,
      putOutBtn,
      ruleCheckBtn,
      ruleConfigBtn,
      confirmAddRulesBtn,
      ActivityDetailBtn,
      Activitycontent,
      loading,
      accessbleRulelist,
      checkedRulesArray,
      activityRules,
      detailContentData,
      handleCheckAllChange,
      handleCheckedRulesChange,
      bookRecordBtn,
      bookRecordsData,
      book_handleCurrentChange,
      putStopOutBtn,
      OrderDetailBtn,
      ...toRefs(orderContent),
      Btnloading
      
    
    };
  },
});
</script>
<style lang="less" scoped>
.el-checkbox{
  margin-left: 10%
}
.rules-font-style{
  font-size: 16px;
  color: rgb(51, 25, 170);
  
}
.goods-list-title {
  display: flex;
  justify-content: center;
  h1 {
    color: rgb(109, 135, 221);
    font-size: 20px;
  }
}
</style>